package com.demo.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.demo.service.impl.RecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.entity.ProductRecord;
import com.demo.entity.User;
import com.demo.repository.ProductRecordRepo;

@RestController
public class UserController {

	@Autowired
	private ProductRecordRepo productRecordRepo;
	@Autowired
	RecordServiceImpl recordServiceImpl;
	
	@RequestMapping(value = "/userIndex")
	public String userIndex(HttpSession session) throws ParseException {
		if (null!=session) {
			User user = (User) session.getAttribute("user");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			String beginStr = sdf1.format(new Date());
			Date tbegin = sdf.parse(beginStr+ " 00:00:00");
			Date tend = sdf.parse(beginStr+" 23:59:59");
			
			Calendar calendar = Calendar.getInstance();
	    	calendar.setTime(new Date());
	    	calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
	    	Date wbegin = calendar.getTime();
			if (null!=user) {
				Integer todayMoney = 0;
				Integer weekMoney = 0;
				Integer totalMoney = 0;
				List<ProductRecord> today = productRecordRepo.findByUserIdAndCreateTimeAfterAndCreateTimeBefore(user.getId(), tbegin, new Date());
				for (ProductRecord productRecord : today) {
					todayMoney = todayMoney + productRecord.getMoney();
				}
				
				List<ProductRecord> week = productRecordRepo.findByUserIdAndCreateTimeAfterAndCreateTimeBefore(user.getId(), wbegin, new Date());
				for (ProductRecord productRecord : week) {
					weekMoney = weekMoney + productRecord.getMoney();
				}
				calendar.set(Calendar.DAY_OF_MONTH, -1);
				List<ProductRecord> total = productRecordRepo.findByUserIdAndCreateTimeAfterAndCreateTimeBefore(user.getId(), calendar.getTime(), new Date());
				for (ProductRecord productRecord : total) {
					totalMoney = totalMoney + productRecord.getMoney();
				}
				Integer rank=recordServiceImpl.getRank(user.getId());
				if (rank==null){
					rank=999999999;
				}
				return "success:"+todayMoney+","+weekMoney+","+user.getName()+","+totalMoney+","+today.size()+","+rank;
			}else{
				return "relogin";
			}
		}
		return "error";
	}
}
